package com.hoo.permission.sdk.web.security.jwt;

import com.hoo.permission.sdk.web.properties.JwtProperties;
import com.hoo.permission.sdk.server.util.SpringContextUtil;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.springframework.util.StringUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

/**
 * jwt 验证过滤器
 *
 * @author hank
 * @create 2020-11-12 下午5:16
 **/

public class HooJwtAuthFilter extends BasicHttpAuthenticationFilter {

   @Override
   protected boolean isLoginAttempt(ServletRequest request, ServletResponse response) {
       return !StringUtils.isEmpty(getToken((HttpServletRequest)request));
   }

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {

        if (isLoginAttempt(request, response)) {
            try {
                executeLogin(request, response);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return true;
    }

    @Override
    protected boolean executeLogin(ServletRequest request, ServletResponse response) throws Exception {
        HooJWTToken token = new HooJWTToken(getToken((HttpServletRequest)request));
        getSubject(request, response).login(token);
        return true;
    }

    private String getToken(HttpServletRequest request) {
        JwtProperties jwtConfig = SpringContextUtil.getBean(JwtProperties.class);
        String token = request.getHeader(jwtConfig.getHeaderName());
        if(StringUtils.isEmpty(token)) {
            token = request.getParameter(jwtConfig.getHeaderName());
        }
        return token;
    }
}
